<?

//using gibi bazi methodlarin bulundugu php sinifi.
require_once("../core.inc.php");
define("CONNECTION_URL", "mysql://user:pass@localhost/joy", true);
define("TABLE_PREFIX", "joy_", true);


using("core.data.persistence.*");

$class_string = '<?php

using("core.data.persistence.*");
using("core.data.tables.*");

class [table]DAO extends Table
{
[fields]
	// Set Initial Members...
	public $prefix = TABLE_PREFIX;
	public $table_pure_name = "[table]";
	public $table_name;

    public static function Get($id)
    {
		return Table::Get([table]DAO, $id);
	}


	public function PrepareFields()
	{
		$this->table_name = "{$this->prefix}{$this->table_pure_name}";

[prepare_fields]	}

///__USER_CODE_START__///[user_code]
///__USER_CODE_END__///

}

?>
';



$con = MDB2::factory(CONNECTION_URL);
if(PEAR::isError($con)) {
    die("Error while connecting : " . $con->getMessage());
}

$q = new Query($con);

$results = $q->Execute("SHOW TABLES;");


foreach ($results as $result)
{
		$t = $result->tables_in_joy;
		$x = split("_", $t);

		if (count($x) > 1)
		{
				$table = $x[1];
				$prefix = $x[0];
		}
		else
		{
			$table = $x[0];
		}

		$class = $class_string;
		$class = str_replace("[table]", $table, $class);
#		$class = str_replace("[prefix]", $prefix, $class);

		$fileName = "$table.php"; 

		$dts = $q->Execute("DESC $t;");

		$prepare_fields = "";
		$fields = "";

		foreach($dts as $dt)
		{
				$fields .= "\tpublic \$$dt->field;\n";
				
				if (strstr($dt->type, "int") == TRUE || strstr($dt->type, "smallint") == TRUE)
				{
						$data_type = "INTEGER";
				}
				else
				{
					$data_type = "STRING";
				}

				if ($dt->key)
				{
						$key = "TableField::$dt->key";

								}
				else
				{
						$key = "null";
				}

				$nullable = ($dt->null) ? "true" : "false";
				$sequence = (($dt->key == "PRI") ? '"1:1"' : "null");

				$has_default = ($dt->default) ? "true" : "false";

				$prepare_fields .= "\t\t".'$this->fields["'.$dt->field.'"] = new TableField("'.
						$dt->field.'", "'.
						$data_type.'", '.
						$nullable.', '.
						$has_default.', '.
						$key.', '.$sequence.');'."\n";
	 
		}

		$class = str_replace("[fields]", $fields, $class);
		$class = str_replace("[prepare_fields]", $prepare_fields, $class);
		$class = str_replace("[user_code]", getUserCode($fileName), $class);

		$file = fopen("../bin/core/data/tables/$fileName", "w+");
		fwrite($file,  $class);
		fclose($file);

}
		echo "Table code generated";


function getUserCode($fileName)
{
	$file_path = "../bin/core/data/tables/$fileName";

	$file = fopen($file_path, "r");
	$content = fread($file, filesize($file_path));

	fclose($file);



	$start=strpos($content, "///__USER_CODE_START__///")+strlen("///__USER_CODE_START__///");
	$end =strpos($content, "///__USER_CODE_END__///");

	$result = trim(substr($content, $start, $end-$start));

	return (strlen($result)>0) ? "\n\n\t".$result."\n" : "";
}



?>
